<template>
    <div class="app">
        <battleInfo
                :player-health="playerHealth"
                :monster-health="monsterHealth"
        />
        <operateBar
                :is-gaming="isGaming"
                @start-game="startGame"
                @give-up="isGaming = !isGaming"
                @attack="attack"
                @special-attack="specialAttack"
                @heal="heal"
        />
        <battleLogs :logs="logs"/>
    </div>
</template>

<script>
import Vue from "vue"
import battleInfo from "./components/battle-info.vue"
import operateBar from "./components/operate-bars.vue"
import battleLogs from "./components/battle-logs.vue"

export default {
  name: "App",
  components: {
    battleInfo,
    operateBar,
    battleLogs
  },
  data: function () {
    return {
      isGaming: false,
      playerHealth: 100,
      monsterHealth: 100,
      logs: []
    }
  },
  methods: {
    startGame () {
      this.playerHealth = 100
      this.monsterHealth = 100
      this.isGaming = true
      this.logs = []
    },
    random (min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min
    },
    attack () {
      const damage = this.random(2, 10)
      this.monsterHealth -= damage
      this.createLog({
        isPlayer: true,
        message: `You attack the monster for ${damage} damage`
      })
      this.winOrLost()
    },
    specialAttack () {
      const damage = Math.round((Math.random() * 2 + 1) * this.random(2, 10))
      this.monsterHealth -= damage
      this.createLog({
        isPlayer: true,
        message: `You use skills:special-attack to give the monster for ${damage} damage`
      })
      this.winOrLost()
    },
    heal () {
      const healNum = Math.min(100 - this.playerHealth, this.random(8, 15))
      this.playerHealth += healNum
      this.createLog({
        isPlayer: true,
        message: `You use skills:Heal to heal yourself for ${healNum} damage`
      })
      this.winOrLost()
    },
    gameOver (isWin) {
      Vue.nextTick(
        function () {
          if (
            confirm(
              (isWin ? "you win!" : "you lost!") +
              "\ndo you need play game again?"
            )
          ) {
            this.startGame()
          } else {
            this.isGaming = false
          }
        }.bind(this)
      )
    },
    winOrLost () {
      if (this.monsterHealth <= 0) {
        // console.log(0)
        this.monsterHealth = 0
        this.gameOver(true)
        return true
      } else {
        const damage = this.random(3, 12)
        this.playerHealth -= damage
        this.createLog({
          isPlayer: false,
          message: `The monster attack you  for ${damage} damage`
        })
        if (this.playerHealth <= 0) {
          this.playerHealth = 0
          this.gameOver(false)
        }
      }
    },
    createLog (obj) {
      this.logs.unshift(obj)
    }
  }
}
</script>
